package com.xiaoyu.shenyou.shenyouv1.services.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xiaoyu.shenyou.shenyouv1.common.position.PositionUtil;
import com.xiaoyu.shenyou.shenyouv1.common.roomname.RoomName;
import com.xiaoyu.shenyou.shenyouv1.common.shenyoucode.ToServerCode;
import com.xiaoyu.shenyou.shenyouv1.common.shenyouentity.RootBean;
import com.xiaoyu.shenyou.shenyouv1.common.shenyouentity.accesstoken.AccessToken;
import com.xiaoyu.shenyou.shenyouv1.common.shenyouentity.userinfo.UserInfo;
import com.xiaoyu.shenyou.shenyouv1.dto.*;
import com.xiaoyu.shenyou.shenyouv1.entity.AutoConfigEntity;
import com.xiaoyu.shenyou.shenyouv1.entity.AutoLogEntity;
import com.xiaoyu.shenyou.shenyouv1.entity.AutoUserEntity;
import com.xiaoyu.shenyou.shenyouv1.mapper.AutoPlayMapper;
import com.xiaoyu.shenyou.shenyouv1.services.AutoPlayService;
import com.xiaoyu.shenyou.shenyouv1.utils.BaseContext;
import com.xiaoyu.shenyou.shenyouv1.utils.ShenyouHttpClient;
import com.xiaoyu.shenyou.shenyouv1.websocketclient.autobettingclient.BettingSocketClient;
import com.xiaoyu.shenyou.shenyouv1.websocketclient.tocliententity.assetinfo.AssetInfo;
import com.xiaoyu.shenyou.shenyouv1.websocketclient.toserverentity.ToServerEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class AutoPlayServiceImpl implements AutoPlayService {

    @Autowired
    private AutoPlayMapper autoPlayMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public AutoUserEntity userLogin(LoginDTO loginDTO) {
        if (StrUtil.isEmpty(loginDTO.getSecret())) {
            return null;
        }
        //查询个人资料
        RootBean userDetail = ShenyouHttpClient.post(null, "/app/businessUser/userDetail", loginDTO.getSecret());
        if (userDetail.getCode() != 200) {
            return null;
        }
        //查询余额
        RootBean asset = ShenyouHttpClient.post(null, "/app/businessUser/myAsset", loginDTO.getSecret());
        AssetInfo assetInfo = JSONUtil.toBean(asset.getData(), AssetInfo.class);
        UserInfo info = JSONUtil.toBean(userDetail.getData(), UserInfo.class);
        AutoUserEntity autoUser = new AutoUserEntity();
        autoUser.setUser_id(info.getId())
                .setHead_mage(info.getHeadImage())
                .setPhone(info.getPhone())
                .setNick_name(info.getNickName())
                .setCreate_time(LocalDateTime.now())
                .setStone(assetInfo.getStoneNum())
                .setToken(loginDTO.getSecret());
        //查询数据库，是否存在
        AutoUserEntity autoUserEntity = autoPlayMapper.selectUserInfoById(info.getId());
        if (ObjectUtil.isNotNull(autoUserEntity)) {
            //更新数据
            autoUser.setIs_auto(autoUserEntity.getIs_auto());
            autoPlayMapper.updateAutoUser(autoUser);
        }
        if (ObjectUtil.isNull(autoUserEntity)) {
            autoUser.setIs_auto(0);
            autoPlayMapper.insertUserInfo(autoUser);
        }
        return autoUser;
    }

    @Override
    public AutoConfigEntity getAutoConfigById(int userId) {
        AutoConfigEntity autoConfig = autoPlayMapper.selectAutoConfigById(userId);
        return autoConfig;
    }

    @Override
    public List<AutoLogEntity> getAutoLogsById(AutoUserDTO autoUserDTO) {
        //先从缓存中读取
        List<AutoLogEntity> autoLogs = (List<AutoLogEntity>) redisTemplate.opsForValue().get("auto_logs" + autoUserDTO.getUser_id());
        if (ObjectUtil.isNull(autoLogs)) {
            autoLogs = autoPlayMapper.selectAutoLogsBySize(autoUserDTO.getUser_id(), 100);
        }
        return autoLogs;
    }

    @Override
    public void updateAutoConfig(AutoConfigDTO autoConfigDTO) {
        AutoConfigEntity autoConfig = new AutoConfigEntity();
        BeanUtils.copyProperties(autoConfigDTO, autoConfig);
        autoConfig.setCreate_time(LocalDateTime.now());
        autoConfig.setIs_skip_betting(autoConfigDTO.getIs_skip_betting() ? 1 : 0);
        AutoConfigEntity autoConfig1 = autoPlayMapper.selectAutoConfigById(autoConfigDTO.getUser_id());
        if (ObjectUtil.isNull(autoConfig1)) {
            //插入一条配置
            autoPlayMapper.insertAutoConfigById(autoConfig);
            return;
        }
        //不为空则更新配置
        autoPlayMapper.updateAutoConfig(autoConfig);
    }

    @Override
    public void updateAuto(AutoPlayDTO autoPlayDTO) {
        AutoUserEntity autoUser = new AutoUserEntity();
        autoUser.setUser_id(autoPlayDTO.getUser_id());
        autoUser.setIs_auto(autoPlayDTO.getIs_auto());
        log.info(autoPlayDTO.toString());
        autoPlayMapper.updateAutoUserIsAuto(autoUser);
    }

    @Override
    public void insertDefaultAutoConfig(AutoUserEntity autoUserEntity) {
        //查询有无默认的auto_config
        AutoConfigEntity autoConfig = autoPlayMapper.selectAutoConfigById(autoUserEntity.getUser_id());
        if (ObjectUtil.isNull(autoConfig)) {
            AutoConfigEntity autoConfig1 = new AutoConfigEntity();
            autoConfig1.setPrediction_name("AI预测法");
            autoConfig1.setUser_id(autoUserEntity.getUser_id());
            autoConfig1.setSize(1);
            autoConfig1.setProfit(100.0);
            autoConfig1.setLose(100.0);
            autoConfig1.setMultiple(5);
            autoConfig1.setWincount_stop(100);

            autoConfig1.setIs_skip_betting(0);
            autoConfig1.setSkip_betting(1);

            autoConfig1.setContinue_fail(10);
            autoConfig1.setMultiple_reset(3);
            autoConfig1.setContinue_fail_skip(0);
            autoConfig1.setCreate_time(LocalDateTime.now());
            autoPlayMapper.insertAutoConfigById(autoConfig1);
        }
    }

    @Override
    public boolean changRoom(ChangRoomDTO changRoomDTO) {
        int userId = changRoomDTO.getUser_id();
        BettingSocketClient bettingSocketClient = BettingSocketClient.WEBSOCKET_CLIENT_MAP.get(userId);
        if (ObjectUtil.isNull(bettingSocketClient)) {
            return false;
        }
        //房间名字获取id
        String nextRoomName = changRoomDTO.getRoomName();
        Integer nextRoomId = RoomName.getIdByRoomName.get(nextRoomName);
        ToServerEntity toServerEntity = new ToServerEntity();
        toServerEntity.setCode(ToServerCode.SELECT_ROOM)
                .setGameType(2)
                .setUid(changRoomDTO.getUser_id())
                .setRoomId(nextRoomId)
                .setPosition(PositionUtil.getPositionById.get(nextRoomId));
        bettingSocketClient.send(JSONUtil.toJsonStr(toServerEntity));
        bettingSocketClient.getAutoLog().setPrediction(nextRoomName);
        return true;
    }

    /**
     * 发送验证码
     *
     * @param phoneDTO
     */
    @Override
    public RootBean sendMsg(PhoneDTO phoneDTO) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("codeType", 2);
        paramMap.put("phone", phoneDTO.getPhone());
        RootBean post = ShenyouHttpClient.postNotToken(paramMap, "/app/businessUser/sendCode");
        return post;
    }

    @Override
    public RootBean submitPhoneAndCode(CodeDTO codeDTO) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", codeDTO.getPhone());
        paramMap.put("code", codeDTO.getCode());
        RootBean post = ShenyouHttpClient.postNotToken(paramMap, "/app/businessUser/phoneLogin");
        return post;
    }
}
